﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
using System.ComponentModel;
//sing System.Windows.Forms;
using System.IO;



using SimulationTimer;
using ForexHistory;
using Common;

namespace ForexSimulator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private SimulationTimer.Clock _clock;
        private Thread _th;
        private Thread _data;
        private bool _active = false;
        private ForexHistory.CurrencyHistoryManager _history;
        private ResponseHistoryList _responses = null;

        public MainWindow()
        {
            _clock = new SimulationTimer.Clock();
            _clock.OnTimeNotify += _clock_OnTimeNotify;
            DataContext = _clock;

            InitializeComponent();

            cbPairs.ItemsSource = Enum.GetValues(typeof(CurrencyPair)).Cast<CurrencyPair>();

            cbPeekCurrencyList.ItemsSource = Enum.GetValues(typeof(CurrencyPair)).Cast<CurrencyPair>();
            cbPeekCurrencyList.SelectedIndex = 2;
        }

        protected void _clock_OnTimeNotify(object sender, TimeNotifyEventArgs e)
        {

        }

        private void buStart_Click(object sender, RoutedEventArgs e)
        {
            if (!_active)
            {

                _clock.SimulationStartDate = (DateTime)dpStart.SelectedDate;
                _clock.SimulationEndDate = (DateTime)dpEnd.SelectedDate;
                _clock.Interval = Convert.ToDouble(tbFactor.Text);


                ThreadStart start = delegate()
                {
                    _clock.Start();
                };

                _th = new Thread(start);
                _th.Start();


                buStart.Content = "Pause";
            }
            else
            {
                _th.Suspend();

                buStart.Content = "Start Simulation";
            }

        }

        private void buEnd_Click(object sender, RoutedEventArgs e)
        {

            _th.Abort();

        }

        private void buLoadData_Click(object sender, RoutedEventArgs e)
        {
            string folder = tbFolder.Text;
            _history = new ForexHistory.CurrencyHistoryManager();
            _history.OnError += _OnError;
            _history.OnUpdateStatus += _OnUpdateStatus;
            //_history.OnLoadCompleted += _history_OnLoadCompleted;
            _history.ToLoad = tbFolder.Text;



            _history.LoadGBPUSD = (bool)cbLoadGBPUSD.IsChecked;
            _history.LoadUSDJPY = (bool)cbLoadUSDJPY.IsChecked;
            _history.LoadEURUSD = (bool)cbLoadEURUSD.IsChecked;
            _history.LoadUSDCHF = (bool)cbLoadUSDCHF.IsChecked;

            _history.Start = ((DateTime)dpStart.SelectedDate).Year;
            _history.End = ((DateTime)dpEnd.SelectedDate).Year;

            _history.SearchForSourceFiles();

            ThreadStart start = delegate()
            {
                _history.StartLoad();    
            };

            _data = new Thread(start);
            _data.Start();



        }



        private void buAddFolder_Click(object sender, RoutedEventArgs e)
        {
            /*
            FolderBrowserDialog _fd = new FolderBrowserDialog();

            _fd.ShowNewFolderButton = true;
            if (_fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                tbFolder.Text = _fd.SelectedPath;
            */
        }

        private void buLoadToggle_Click(object sender, RoutedEventArgs e)
        {
            if (_data.ThreadState == ThreadState.Suspended)
                _data.Resume();
            else
                _data.Suspend();
        }

        private RichTextBox GetStatusBox(CurrencyPair pair)
        {
            switch (pair)
            {
                case (CurrencyPair.EURUSD):
                    return rbEURUSD;
                case (CurrencyPair.GBPUSD):
                    return rbGBPUSD;
                case (CurrencyPair.USDCHF):
                    return rbUSDCHF;
                case (CurrencyPair.USDJPY):
                    return rbUSDJPY;
                default:
                    return rbStatus;
            }

        }

        private RichTextBox GetErrorBox(CurrencyPair pair)
        {
            switch (pair)
            {
                case (CurrencyPair.EURUSD):
                    return rbEURUSDError;
                case (CurrencyPair.GBPUSD):
                    return rbGBPUSDError;
                case (CurrencyPair.USDCHF):
                    return rbUSDCHFError;
                case (CurrencyPair.USDJPY):
                    return rbUSDJPYError;
                default:
                    return rbError;
            }

        }

        #region Status/Error Updates

        protected void _OnError(object sender, Common.SimulationErrorEventArgs e)
        {
            UpdateError(e.Error, e.Pair);
        }

        protected void _OnUpdateStatus(object sender, Common.ProgressEventArgs e)
        {
            UpdateStatus(e.Status, e.Pair);
        }

        private void UpdateStatus(string message, CurrencyPair pair)
        {

            Action workAction = delegate
            {

                RichTextBox _toUpdate = GetStatusBox(pair);

                TextRange rangeOfText1 = new TextRange(_toUpdate.Document.ContentEnd, _toUpdate.Document.ContentEnd);
                rangeOfText1.Text = message + Environment.NewLine;
                rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
                rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                _toUpdate.ScrollToEnd();
            };

            System.Windows.Application.Current.Dispatcher.BeginInvoke(
            DispatcherPriority.Background,
               workAction);

        }

        private void UpdateError(string message, CurrencyPair pair)
        {
            Action workAction = delegate
            {
                RichTextBox _toUpdate = GetErrorBox(pair);

                TextRange rangeOfText1 = new TextRange(_toUpdate.Document.ContentEnd, _toUpdate.Document.ContentEnd);
                rangeOfText1.Text = message + Environment.NewLine;
                rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
                rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                _toUpdate.ScrollToEnd();
            };

            System.Windows.Application.Current.Dispatcher.BeginInvoke(
            DispatcherPriority.Background,
               workAction);
        }

        #endregion

        private void buRequestNow_Click(object sender, RoutedEventArgs e)
        {
            if (_responses == null)
            {
                _responses = new ResponseHistoryList();
                dgRequests.ItemsSource = _responses;
            }

            CurrencyPair _toRequest = (CurrencyPair)cbPairs.SelectedValue;

            DateTime _beginRequest = DateTime.Now;


            DateTime _d = _clock.CurrentTime;
            Tick _t = _history.GetTick(_toRequest, _d);

            DateTime _endRequest = DateTime.Now;

            Response _r = new Response();
            _r.TickTime = _t.TickTime;
            _r.RateBid = _t.RateBidRaw;
            _r.RateAsk = _t.RateAskRaw;
            _r.MS = (_beginRequest - _endRequest).TotalMilliseconds;
            _r.Ticks = (_beginRequest - _endRequest).Ticks;
            _r.RequestTime = _d;

            _responses.Add(_r);

        }

        private void buTakeAPeek_Click(object sender, RoutedEventArgs e)
        {

            DateTime _t = (DateTime)dpPeekDate.SelectedDate;
            
            DateTime _date = new DateTime(_t.Year, _t.Month, _t.Day, Convert.ToInt32(cbTimePicker.SelectionBoxItem.ToString()), 0, 0);

            dgPeek.ItemsSource = _history.GetHour((CurrencyPair)cbPeekCurrencyList.SelectedItem, _date);

        }
    }
}
